<template>
  <template v-if="current">
    <el-text
      v-if="mode === 'label'"
      v-bind="$attrs"
      :class="{
        'status-label': true,
        [mode]: true,
        dot: dot,
      }"
      :style="{
        color: colorstr,
      }"
    >
      {{ current?.label }}
    </el-text>
    <el-tag
      v-else-if="mode === 'tag'"
      :class="{
        'status-label': true,
        [mode]: true,
      }"
      v-bind="{
        ...$attrs,
        ...curTagProps,
      }"
    >
      {{ current?.label }}
    </el-tag>
  </template>
</template>

<script lang="ts" setup>
import { statusLabelProps } from './types';

defineOptions({ name: 'StatusLabel' });

const props = defineProps(statusLabelProps);

const colorMap = {
  primary: 'var(--el-color-primary)',
  danger: 'var(--el-color-error)',
  warning: 'var(--el-color-warning)',
  success: 'var(--el-color-success)',
  info: 'var(--el-text-color-regular)',
} as const;

const isHexColor = (v: string) => /^#?([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$/.test(v);

const current = computed(() => {
  const { value, options } = props;
  return options.find((v) => v.value === value);
});

const colorstr = computed(() => {
  if (typeof current.value === 'undefined') return colorMap.info;
  const { color } = current.value;
  if (color && color in colorMap) {
    return colorMap[color as keyof typeof colorMap];
  }
  if (isHexColor(color as string)) {
    return color;
  }
  return colorMap.info;
});

const curTagProps = computed<any>(() => {
  const { color = '' } = current.value || {};
  if (color === 'primary') return {};
  if (color && color in colorMap) {
    return { type: color };
  }
  if (isHexColor(color)) {
    return { color };
  }
  return { type: 'info' };
});
</script>

<style lang="scss" scoped>
.status-label {
  margin-left: 5px;

  & + .status-label {
    margin-left: 5px;
  }
}

.dot {
  &::before {
    display: inline-block;
    width: 6px;
    height: 6px;
    margin-right: 5px;
    margin-bottom: 2px;
    content: '';
    background-color: v-bind(colorstr);
    border-radius: 50%;
  }
}
</style>
